import { cloneDeep } from 'lodash';
import { ComputedRef, onMounted, ref, watch } from 'vue';
import { EmitsType, TableOptions } from '../src/types';

export const useEditRow = (
  useEditRowEdit: EmitsType<'update:editRowTarget'>,
  data: any[],
  editRowTarget: string,
  isEditRow: boolean,
  actionOption: ComputedRef<TableOptions | undefined>,
) => {
  const tableData = ref<any[]>(cloneDeep(data));

  // 编辑行
  const cloneEditRowIndex = ref<string>(editRowTarget);

  onMounted(() => {
    tableData.value.forEach((item) => {
      item.rowEdit = false;
    });
  });

  watch(
    () => editRowTarget,
    (val) => {
      val && (cloneEditRowIndex.value = val);
    },
  );

  // 点击行的事件
  const rowClick = (row: any, column: any) => {
    // 判断是否是点击的操作项
    if (column.label === actionOption.value?.label) {
      if (isEditRow && cloneEditRowIndex.value === editRowTarget) {
        // 编辑行的操作
        row.rowEdit = !row.rowEdit;
        // 重置其他数据的rowEdit
        tableData.value.forEach((item) => {
          if (item !== row) item.rowEdit = false;
        });
        // 重置按钮的标识
        if (!row.rowEdit) useEditRowEdit('update:editRowTarget', '');
      }
    }
  };

  return {
    tableData,
    cloneEditRowIndex,
    rowClick,
  };
};
